package com.example.recordingpen_datacollection.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.api.R;
import com.example.recordingpen_datacollection.Utils.String.StringValidator;
import com.example.recordingpen_datacollection.Utils.Token.UniqueTokenUtil;
import com.example.recordingpen_datacollection.config.AOP.annotation.PreventRepeatSubmit;
import com.example.recordingpen_datacollection.entity.*;
import com.example.recordingpen_datacollection.entity.Vo.LoginVo;
import com.example.recordingpen_datacollection.redisService.RedisService;
import com.example.recordingpen_datacollection.result.RLIST;
import com.example.recordingpen_datacollection.service.*;
import io.swagger.annotations.ApiOperation;
import org.apache.ibatis.annotations.Delete;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author xg
 * @since 2023-11-08
 */
@RestController
@RequestMapping("/login")
public class LoginController {


    @Autowired
    private LoginService loginService;
    @Autowired
    private RedisService redisService;
    @Autowired
    private FrequencyService frequencyService;
    @Autowired
    private IdentificationService identificationService;
    @Autowired
    private UserdevmessService userdevmessService;
    @Autowired
    private LogDelAccountService logDelAccountService;
    @Autowired
    private AccountAuthorityService accountAuthorityService;

    @ApiOperation(value =  "验证登录接口【第一次登录直接注册】")
    @GetMapping("/register")
    public RLIST login2(LoginVo loginVo){


        String phone = loginVo.getPhone();
        boolean phoneNumber = StringValidator.isValidPhoneNumber(phone);
        if(!phoneNumber){
            return RLIST.error().message("手机号异常");
        }

        Object value = redisService.getValue(phone);
        if(value == null){
            return RLIST.error().message("验证码不存在");
        }
        if(!loginVo.getVerification().equals(value.toString()) ){
            return RLIST.error().message("验证码不匹配");
        }

        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("account",phone);
        wrapper.eq("password",phone);
        Login one = loginService.getOne(wrapper);
        Login login = null;
        if(one == null){
            login = loginService.registerMessage(phone);
            if(login ==null){
                return RLIST.error().message("创建失败无法登录");
            }
        }
        //生成token
        String token = UniqueTokenUtil.generateToken();
//        System.out.println(redisService  +" redisService");
        String value1 = (String) redisService.getValue(login.getId().toString());
        if(value1 != null){
            redisService.delKeyData(value1);
        }
        redisService.setTokenValueDAYS(token,1L, login.getId());
        redisService.setTokenValueDAYS(login.getId().toString(),1L,token);
        redisService.delKeyData(phone);
        return RLIST.ok().data("token",token);
    }


    @ApiOperation(value =  "账号密码登录接口")
    @GetMapping("/login")
    public RLIST login(Login login){
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("account",login.getAccount());
        wrapper.eq("password",login.getPassword());
        Login one = loginService.getOne(wrapper);
        if(one == null){
            return RLIST.error().message("账号不存在");
        }
        //生成token
        String token = UniqueTokenUtil.generateToken();
        String value1 = (String) redisService.getValue(one.getId().toString());
        if(value1 != null){
            redisService.delKeyData(value1);
        }
        redisService.setTokenValueDAYS(token,1L, one.getId());
        redisService.setTokenValueDAYS(one.getId().toString(),1L,token);
        return RLIST.ok().data("token",token);
    }

    @ApiOperation(value =  "验证码登录接口")
    @PostMapping("/authLogin")
    public RLIST authLogin(@RequestBody LoginVo loginVo){
        String phone = loginVo.getPhone();
        Object value = redisService.getValue(phone);
        if(value == null){
            return RLIST.error().message("验证码不存在");
        }
        if(!loginVo.getVerification().equals(value.toString()) ){
            return RLIST.error().message("验证码不匹配");
        }



        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("phone",loginVo.getPhone());
        Login one = loginService.getOne(wrapper);
        if(one == null){
            return RLIST.error().message("账号不存在");
        }
        //生成token
        String token = UniqueTokenUtil.generateToken();
        String value1 = (String) redisService.getValue(one.getId().toString());
        if(value1 != null){
            redisService.delKeyData(value1);
        }
        redisService.setTokenValueDAYS(token,1L, one.getId());
        redisService.setTokenValueDAYS(one.getId().toString(),1L,token);

        return RLIST.ok().data("token",token);
    }
    @ApiOperation(value = "获取验证码")
    @GetMapping("getVerification")
    public RLIST getVerification(@RequestParam("phone")String phone){
        boolean phoneNumber = StringValidator.isValidPhoneNumber(phone);
        if(!phoneNumber){
            return RLIST.error().message("手机号异常");
        }


        Object value = redisService.getValue(phone);
        if(value != null){
            return RLIST.error().message("验证码未过期");
        }
        {
            //记录表
            QueryWrapper wrapper = new QueryWrapper();
            wrapper.eq("phone",phone);
            Frequency one = frequencyService.getOne(wrapper);
            Frequency frequency = null;
            if(one == null){
                frequency = new Frequency();
                frequency.setPhone(phone);
                frequency.setCount(1);
                frequencyService.save(frequency);
            }else {
                if(one.getCount()>=5){
                    return RLIST.error().message("今日获取验证码上限");
                }
                frequency = new Frequency();
                frequency.setVerId(one.getVerId());
                frequency.setCount(one.getCount()+1);
                frequencyService.updateById(frequency);
            }
        }
        boolean b = loginService.registerAcc(phone);
        Object value2 = redisService.getValue(phone);
        if(b){

        }
        return RLIST.ok();
    }

    @ApiOperation(value = "参数添加数据接口")
    @PostMapping("register")
    public RLIST register(@RequestBody  LoginVo loginVo){
        /**
         * 参数校验
         * ..........
         */
        Object value = redisService.getValue(loginVo.getPhone());
        if(value == null){
            return RLIST.error().message("验证码不存在");
        }
        if(!loginVo.getVerification().equals(value.toString()) ){
            return RLIST.error().message("验证码不匹配");
        }
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("phone", loginVo.getPhone());
        int count = loginService.count(wrapper);
        if(count != 0){
            return RLIST.error().message("手机存在不能创建");
        }

        QueryWrapper wrapper2 = new QueryWrapper();
        wrapper2.eq("account", loginVo.getAccount());
        int count2 = loginService.count(wrapper2);
        if(count2 != 0){
            return RLIST.error().message("账号存在不能创建");
        }

        Login login = new Login();
        login.setPhone(loginVo.getPhone());
        login.setAccount(loginVo.getAccount());
        login.setPassword(loginVo.getPassword());
        boolean save = loginService.save(login);
        if(save){
            redisService.delKeyData(loginVo.getPhone());
            return RLIST.ok();
        } else {
            return RLIST.error();
        }

    }


    @ApiOperation(value = "手机号秒注册")
    @PostMapping("register2")
    public RLIST register2(@RequestBody LoginVo loginVo){

        Object value = redisService.getValue(loginVo.getPhone());
        if(value == null){
            return RLIST.error().message("验证码不存在");
        }
        if(!loginVo.getVerification().equals(value.toString()) ){
            return RLIST.error().message("验证码不匹配");
        }

        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("phone", loginVo.getPhone());
        int count = loginService.count(wrapper);
        if(count != 0){
            return RLIST.error().message("手机存在不能创建");
        }
        String phone = loginVo.getPhone();
        Login login = new Login();
        login.setAccount(phone);
        login.setPassword(loginVo.getPassword());
        login.setPhone(loginVo.getPhone());
        boolean save = loginService.save(login);
        if(save){
            return RLIST.ok();
        } else {
            return RLIST.error();
        }

    }

    @ApiOperation(value = "账号秒注册")
    @GetMapping("account2")
    @PreventRepeatSubmit(interval = 1)
    public RLIST account2(@RequestParam("account")String account,@RequestParam("companyType")String companyType){

        /**
         * 标识绑定
         */
        QueryWrapper wrapper1 = new QueryWrapper();
        wrapper1.eq("company_logo",companyType);
        Identification one1 = identificationService.getOne(wrapper1);
        if(one1 == null){
            return RLIST.error().message("标识不存在");
        }
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("account", account);
        Login one = loginService.getOne(wrapper);
        if(one != null){
            //生成token
            String token = UniqueTokenUtil.generateToken();
            String value1 = (String) redisService.getValue(one.getId().toString());
            if(value1 != null){
                redisService.delKeyData(value1);
            }
            redisService.setTokenValueDAYS(token,1L, one.getId());
            redisService.setTokenValueDAYS(one.getId().toString(),1L,token);
            return RLIST.ok().data("token",token);
        }




        String phone = account;
        Login login = loginService.registerMessage(phone,one1);
        //生成token
        String token = UniqueTokenUtil.generateToken();
        String value1 = (String) redisService.getValue(login.getId().toString());
        System.out.println("不存在");
        if(value1 != null){
            redisService.delKeyData(value1);
        }
        redisService.setTokenValueDAYS(token,1L, login.getId());
        redisService.setTokenValueDAYS(login.getId().toString(),1L,token);

        if(login!=null){
            return RLIST.ok().data("token",token);
        } else {
            return RLIST.error();
        }

    }

    @ApiOperation(value = "获取告示")
    @GetMapping("getBulletin")
    public RLIST getBulletin(HttpServletRequest request){
        String token = request.getHeader("token");
        if( token.length() != 36 ){
            return RLIST.error().message("无权操作");
        }
        Integer value = (Integer) redisService.getValue(token);

        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("login_id",value);

        AccountAuthority one = accountAuthorityService.getOne(wrapper);
        if(one == null){
            return RLIST.error();
        }
        Map<String,String> map = new HashMap<>();
        map.put("title",one.getTitle());
        map.put("message",one.getMessage());
        return RLIST.ok().data("data",map);
    }


    @ApiOperation(value = "设备的删除接口")
    @DeleteMapping("delDevice")
    public RLIST delDevice(@RequestParam("devid")Integer devid,HttpServletRequest request){
        String token = request.getHeader("token");
        if( !(token.length() == 56) ){
            return RLIST.error().message("无权操作");
        }
        Integer value = (Integer) redisService.getValue(token);

        Login byId = loginService.getById(devid);
        if(byId == null){
            return RLIST.error().message("设备不存在");
        }
        LogDelAccount logDelAccount = new LogDelAccount();
        logDelAccount.setDelName(byId.getAccount());
        logDelAccount.setDelType("device");
        logDelAccount.setDelAccount(byId.getAccount());
        logDelAccount.setDelHandlersId(value);
        logDelAccount.setDelHandlersType("Admin");
        logDelAccountService.setLogDelAcc(logDelAccount);
        boolean delDevice= loginService.delDevice(devid);
        if(delDevice){
            return RLIST.ok();
        } else {
            return RLIST.error();
        }
    }

}

